<template>
  <div class="page-wrapper">
    <div class="main-content-panels">
      <LeftPanel
        :currentDevice="currentDeviceObject.name"
        :currentDeviceImageName="currentDeviceObject.imageName"
        :sensorPoints="currentDeviceObject.sensorPoints"
        :devices="devices"
        :activeDeviceName="currentDeviceObject.name"
        @switch-device="switchDevice"
        @sensor-clicked="handleSensorClick"
        v-if="currentDeviceObject.name"
      />
      <div class="right-panel-placeholder">
        <RightPanel
          :currentDevice="currentDeviceObject.name"
          :currentDeviceObject="currentDeviceObject"
          :activeSensorId="activeSensorIdForRightPanel"
          @view-fault-detail="handleViewFaultDetail"
          @navigate-to-fault-tracing="navigateToFaultTracing"
          @sensor-clicked="handleSensorClick"
          v-if="currentDeviceObject.name"
        />
        <div v-else class="loading-placeholder">
          <p>装置信息加载中...</p>
          <div class="spinner"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import LeftPanel from '../components/AnomalyDetection/LeftPanel.vue'
import RightPanel from '../components/AnomalyDetection/RightPanel.vue'

const router = useRouter()
const route = useRoute() // 获取路由信息

// 存储从后端获取的所有装置列表 (仅 id 和 name)
const devices = ref([]) // [{ id: 'dev_union_alcohol', name: '联醇装置' }, ...]

// 存储当前选中的装置的完整信息 (从 /api/devices/{deviceId}/sensors 接口获取)
const currentDeviceObject = ref({}) // { id, name, sensorPoints: [], info: {} }
const currentDeviceName = computed(() => currentDeviceObject.value.name) // 方便传递给子组件

// 故障信息数据 (仍在前端硬编码，由 AnomalyDetectionMain 管理，并传递给 RightPanel)
// 假设这是装置的基础信息，不再从后端获取 fault-info 接口
const HARDCODED_DEVICE_INFO = {
  联醇装置: {
    name: '联醇装置',
    responsiblePerson: '张三',
    todayEnergyConsumption: '1500 kWh',
    runningStatus: '稳定运行',
    lastMaintenance: '2025-03-10',
    currentAmbientTemperature: '25°C',
    systemVersion: 'V2.1.0',
  },
  解吸浓缩系统装置: {
    name: '解吸浓缩系统装置',
    responsiblePerson: '李四',
    todayEnergyConsumption: '800 kWh',
    runningStatus: '待机',
    lastMaintenance: '2025-02-01',
    currentAmbientTemperature: '23°C',
    systemVersion: 'V2.1.0',
  },
}

const activeSensorIdForRightPanel = ref(null)
let simulateInterval = null

/**
 * 【修改】从硬编码数据中获取所有装置列表。
 */
const getHardcodedDeviceList = () => {
  console.log('AnomalyDetectionMain: Using hardcoded device list.')
  // 使用原有的 Mock 数据作为硬编码列表
  const hardcodedDevices = [
    {
      id: 'dev_union_alcohol',
      name: '联醇装置',
      imageName: 'device.png',
    },
    {
      id: 'dev_desorption_system',
      name: '解吸浓缩系统装置',
      imageName: 'device1.png',
    },
    {
      id: 'dev_denox_system_1', // 注意：为防止ID重复，给烟气脱硝装置改了ID
      name: '烟气脱硝装置',
      imageName: 'device1.png',
    },
  ]
  devices.value = hardcodedDevices
  console.log('AnomalyDetectionMain: Device list loaded from hardcode:', devices.value)

  if (devices.value.length > 0) {
    const deviceNameFromQuery = router.currentRoute.value.query.deviceName
    let initialDeviceId = devices.value[0].id // 默认选中第一个

    if (deviceNameFromQuery) {
      const targetDevice = devices.value.find((d) => d.name === deviceNameFromQuery)
      if (targetDevice) {
        initialDeviceId = targetDevice.id
      } else {
        console.warn(
          `AnomalyDetectionMain: Device '${deviceNameFromQuery}' from query not found in hardcode. Defaulting to first device.`,
        )
      }
    }
    // 注意：fetchCurrentDeviceDetails 仍需 await，因为它内部仍调用接口
    return fetchCurrentDeviceDetails(initialDeviceId)
  }
}

/**
 * 根据装置ID获取当前装置的传感器位置和实时数据。
 * @param {string} deviceId - 装置的唯一ID。
 */
const fetchCurrentDeviceDetails = async (deviceId) => {
  const selectedDevice = devices.value.find((d) => d.id === deviceId)
  if (!selectedDevice) {
    console.error(`AnomalyDetectionMain: Device with ID ${deviceId} not found.`)
    return
  }

  try {
    console.log(
      `AnomalyDetectionMain: Fetching sensors for device ${selectedDevice.name} from /api/devices/${selectedDevice.id}/sensors...`,
    )
    const response = await fetch(`/api/devices/${selectedDevice.id}/sensors`)
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const sensorData = await response.json()

    currentDeviceObject.value = {
      id: selectedDevice.id,
      name: selectedDevice.name,
      imageName: selectedDevice.imageName, // <-- 关键：这里将 imageName 整合进来 [cite: 14]
      info: HARDCODED_DEVICE_INFO[selectedDevice.name] || {},
      sensorPoints: sensorData,
    }
    console.log(`AnomalyDetectionMain: Details for ${selectedDevice.name} loaded.`)
  } catch (error) {
    console.error(
      `AnomalyDetectionMain: Error fetching details for device ${selectedDevice.name}, using mock data:`,
      error,
    )
    // Fallback mock sensors and device info
    const mockSensorData =
      selectedDevice.name === '联醇装置'
        ? [
            {
              id: 'FIC1001',
              top: '35.4%',
              left: '41.5%',
              colorCategory: '主要',
              latestValue: 55.6,
              unit: 'm³/h',
              timestamp: new Date().toISOString(),
            },
            {
              id: 'FIC1002',
              top: '81.1%',
              left: '36.5%',
              colorCategory: '相关',
              latestValue: 12.3,
              unit: 'kPa',
              timestamp: new Date().toISOString(),
            },
            {
              id: 'PIC1003',
              top: '50%',
              left: '60%',
              colorCategory: '其他',
              latestValue: 8.9,
              unit: 'Mpa',
              timestamp: new Date().toISOString(),
            },
          ]
        : [
            {
              id: 'FI615',
              top: '9%',
              left: '55%',
              colorCategory: '主要',
              latestValue: 68.1,
              unit: '℃',
              timestamp: new Date().toISOString(),
            },
            {
              id: 'TE203',
              top: '35%',
              left: '12%',
              colorCategory: '相关',
              latestValue: 35.7,
              unit: 'm/s',
              timestamp: new Date().toISOString(),
            },
            {
              id: 'LI301',
              top: '20%',
              left: '80%',
              colorCategory: '其他',
              latestValue: 75.0,
              unit: '%',
              timestamp: new Date().toISOString(),
            },
          ]
    currentDeviceObject.value = {
      id: selectedDevice.id,
      name: selectedDevice.name,
      imageName: selectedDevice.imageName, // <-- 关键：Fallback 时也确保有 imageName [cite: 23]
      info: HARDCODED_DEVICE_INFO[selectedDevice.name] || {},
      sensorPoints: mockSensorData,
    }
  }
  activeSensorIdForRightPanel.value = null // 切换装置时清空已选中的传感器
}

/**
 * 处理装置切换事件。
 * @param {string} deviceName - 被选择的装置名称。
 */
const switchDevice = async (deviceName) => {
  const selectedDevice = devices.value.find((d) => d.name === deviceName)
  if (selectedDevice) {
    await fetchCurrentDeviceDetails(selectedDevice.id)
    console.log('AnomalyDetectionMain: Device switched to:', deviceName)
  } else {
    console.warn(`AnomalyDetectionMain: Device '${deviceName}' not found.`)
  }
}

/**
 * 模拟传感器数据的实时更新 (如果后端 /api/devices/{deviceId}/sensors 不做实时更新，前端可以自行更新 latestValue)。
 */
const simulateSensorDataUpdate = () => {
  if (currentDeviceObject.value && currentDeviceObject.value.sensorPoints) {
    currentDeviceObject.value.sensorPoints.forEach((point) => {
      point.latestValue = parseFloat((point.latestValue + (Math.random() - 0.5) * 0.5).toFixed(1))
      point.latestValue = Math.max(0, Math.min(100, point.latestValue))
      point.timestamp = new Date().toISOString()
    })
  }
}

/**
 * 处理 LeftPanel 的传感器点击事件。
 * @param {string} sensorId - 被点击的传感器ID。
 */
const handleSensorClick = (sensorId) => {
  console.log(
    'AnomalyDetectionMain: Sensor clicked, setting activeSensorId for RightPanel:',
    sensorId,
  )
  activeSensorIdForRightPanel.value = sensorId
}

/**
 * 处理 RightPanel 的“查看故障详情”事件，触发路由跳转。
 */
const handleViewFaultDetail = () => {
  router.push({ name: 'FaultInfo' })
}

/**
 * 处理 RightPanel 的“导航到故障溯源”事件，触发路由跳转。
 * @param {Object} params - 包含 alarmId 和 sensorId 的对象。
 */
const navigateToFaultTracing = (params) => {
  console.log('---------------Params received:', params)
  if (!params.sensorId) {
    console.error('--------------------sensorId is missing or invalid')
  } else {
    router.push({ name: 'FaultTracing', params: params })
  }
}

/**
 * 清空数据并开始模拟的占位函数。
 */
const clearAndStartMonitor = async () => {
  console.log(
    'Simulating Clear and Start Monitor action (calls backend /api/clear, /api/start_monitor).',
  )
  try {
    await fetch('/api/clear')
    await fetch('/api/start_monitor')
    alert('数据已清空并开始模拟！')
    // 重新获取当前装置的传感器数据以刷新模拟状态
    if (currentDeviceObject.value && currentDeviceObject.value.id) {
      await fetchCurrentDeviceDetails(currentDeviceObject.value.id)
    }
  } catch (error) {
    console.error('Failed to clear/start monitor:', error)
    alert('操作失败，请检查后端服务！')
  }
}

// =========================================================
// 生命周期钩子
// =========================================================
onMounted(async () => {
  await getHardcodedDeviceList() // 【修改】改为调用同步获取硬编码列表的函数
  // 启动实时数据模拟器
  if (!simulateInterval) {
    simulateInterval = setInterval(simulateSensorDataUpdate, 2000) // 每2秒更新一次
  }
})

onUnmounted(() => {
  // 清理定时器，防止内存泄漏
  if (simulateInterval) {
    clearInterval(simulateInterval)
    simulateInterval = null
  }
})

// 监听 currentDeviceObject 变化 (主要用于调试)
watch(
  currentDeviceObject,
  (newVal) => {
    console.log('AnomalyDetectionMain: currentDeviceObject changed.', newVal)
  },
  { deep: true },
)
</script>

<style scoped>
.page-wrapper {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  min-height: 0;
  background-color: #f0f2f5;
}

.main-content-panels {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
}

.right-panel-placeholder {
  overflow-y: auto;
  max-height: 100vh;
  width: 500px;
}

/* 移除 .device-controls-bottom 的样式，因为它不再存在 */
</style>
